<%@ page language="java" pageEncoding="utf-8" %>
<%
    String path = request.getContextPath();
    session.setAttribute("path", path);
%>
<!DOCTYPE html>
<html>
<head>
    <%@include file="../common/base.jsp" %>
    <meta charset="utf-8"/>
    <meta name="viewport" content="width=device-width,initial-scale=1,maximum-scale=1,minimum-scale=1"/>
    <meta http-equiv="pragma" content="no-cache">
    <meta http-equiv="Cache-Control" content="no-cache,must-revalidate">
    <meta http-equiv="expires" content="0">
    <title>${appName}</title>
    <link rel="stylesheet" type="text/css" href="${base}/css/bootstrap.min.css">
    <!--城市选择css-->
    <link rel="stylesheet" href="${base}/plugin/cityselect/css/LArea.min.css">
    <!--单列选择-->
    <link rel="stylesheet" href="${base}/plugin/iosselect-master/src/iosSelect.css">

    <link rel="stylesheet" type="text/css" href="${base}/plugin/citysearch/citysearch.css?version=${version}">
    <!---->
    <link rel="stylesheet" type="text/css" href="${base}/css/global.css?version=${version}">
    <link rel="stylesheet" type="text/css" href="${base}/css/index.css?version=${version}">
    <style type="text/css">
        .input {
            -webkit-appearance: none;
            -moz-appearance: none;
            -o-appearance: none;
            appearance: none;
            background-color: #ffffff;
        }

        #historyBox {
            position: fixed;
            top: 50px;
            left: 0;
        }

        .closeExtraDiv {
            position: fixed;
            text-align: center;
        }

        .layui-layer-msg {
            background-color: #585858 !important;
        }

        body {
            position: absolute;
            left: 0;
            right: 0;
            top: 0;
            bottom: 0;
            min-height: 600px;
        }

        .layui-layer {
            overflow: hidden;
        }

        .layui-layer-content {
            position: relative;
            border-bottom-left-radius: 10px;
            border-bottom-right-radius: 10px;
            overflow: hidden;
        }

        .layui-layer-title {
            height: 30px;
            line-height: 30px;
        }
    </style>
</head>
<body>
<input type="hidden" value="" id="inputId">
<input type="hidden" value="0" id="valueTo">
<input type="hidden" value="" id="curLocation">
<input type="hidden" value="${sessionScope.passengerUuid}" id="passengerUuid">
<div id="container" class="hide"></div>
<div id="searchBox" class="container-fluid">

</div>
<div id="mask"></div>
<div id="historyBox" class=""></div>
<div id="containerBox" class="container-fluid">
    <div class="header clearfix text-center">
        <div class="pull-left">
            <div class="user-face-icon">
                <img class="img" src="${base}/images/man.png">
            </div>
        </div>
        <%--<span class="title">专车</span>--%>
    </div>
    <p class="text-center tips">您好，您现在想去哪儿？</p>
    <div class="info-container">
        <div style="text-align: center;">
            <span id="setoutTime" class="text-center setoutTime">
                <img class="img timeshow" src="${base}/images/time.png">
                <span id="timeshow" class="timeshow">现在</span>
            </span>
        </div>

        <ul class="addr-inputs">
            <li class="li qidian">
                <img class="img" src="${base}/images/qidian.png">
                <span class="input qidian-input" id="qidian_input" style="display: inline-block;">您从哪上车</span>
            </li>
            <li class="li zhongdian">
                <img class="img" src="${base}/images/zhongdian.png">
                <span id="zhongdian_input" class="input" style="display: inline-block;">您要去哪儿</span>
            </li>
        </ul>
        <div class="row takeman hide">
            <p id="changeCustomer" class="col-xs-6 p">
                <img src="${base}/images/order_icon_user@3x.png">
                <span id="changeCustomerSpan">换乘车人</span>
            </p>
            <p id="selectCarType" class="col-xs-6 p">
                <img src="${base}/images/Shape.png">
                <span id="carTypeText" data-id="" data-value="">选择车型</span>
            </p>
        </div>
        <div class="costBox hide" style="text-align: center;">
            <div style="display: inline-block;">
                <p class="text-center cost fare-info">约<span id="moneyText" class="money">0</span>元</p>
                <p class="text-center sub" style="font-size: 14px;display: none;" id="actPaid">券已抵扣 <span>0</span>元</p>
            </div>
        </div>
    </div>
    <div class="btn-call btn-call-disabled" style="text-decoration:none;">呼叫专车</div>
</div>
<%--侧边导航--%>
<div class="nav_mask"></div>
<div class="l-left-nav">
    <div class="user-info">
        <div class="user-face"><img src="${image}" class="" alt=""></div>
        <div class="user-name"> ${nickName} </div>
        <div class="user-mobile"></div>
    </div>
    <div class="Rectangle-16-Copy-6"></div>
    <div class="nav-list">
        <a href="${base}/yue/order_list" class="trip">我的行程</a>
        <a href="${base}/yue/couponlist" class="couponlist">优惠券</a>
        <a href="javascript:void(0)" class="exit" id="exit">退出</a>
    </div>
</div>

<div class="l-footer" style="position: absolute;">
    <%@include file="footer.jsp" %>
</div>

</body>
<script type="text/javascript" src="${base}/js/jquery.min.js"></script>
<script type="text/javascript" src="${base}/plugin/layer-v3.0.3/layer.js"></script>

<script type="text/javascript"
        src="https://webapi.amap.com/maps?v=1.3&key=55897440ff54932c599cc73b9b4baf1c&plugin=AMap.Autocomplete,AMap.PlaceSearch,AMap.Driving,AMap.CitySearch,AMap.Geolocation"></script>
<script src="${base}/plugin/cityselect/js/LAreaData1.js" type="text/javascript"></script>
<script src="${base}/plugin/cityselect/js/LArea.js" type="text/javascript"></script>

<script src="${base}/js/carType.js"></script>
<script src="${base}/plugin/iosselect-master/src/iscroll.js"></script>
<script src="${base}/plugin/iosselect-master/src/iosSelect.js"></script>

<script type="text/javascript" src="${base}/js/localStorageOpt.js?version=${version}"></script>
<script type="text/javascript" src="${base}/js/constant.js?version=${version}"></script>
<script type="text/javascript" src="${base}/js/position.js?version=${version}"></script>
<script type="text/javascript" src="${base}/js/utils.js?version=${version}"></script>

<script type="text/javascript" src="${base}/js/search.js?version=${version}"></script>

<script type="text/javascript" src="${base}/plugin/citysearch/citysearch.js?version=${version}"></script>

<script type="text/javascript">
    var yun = new yueajax("${openId}");
    (function () {
        setLocalStorage('ifBindWxUser', "false")
        setLocalStorage('isH5', "true")
        delLocalStorage("yueuser")
        var us = getLocalStorage("yueuserH5", "object");
        if (!!us) {
            setLocalStorage('ifBindWxUser', "true")
            $(".user-face").find('img').attr("src", us.face || "${base}/images/man.png");
            $(".user-name").html(us.nickname || "未填写");
            $(".user-mobile").html((us.mobile).replace(/(\d{3})\d{4}(\d{4})/, '$1****$2'));

            yun.ajax_md5(
                {token: us.token},
                "/api/v1/passenger/token/order/status",
                function (data) {
                    var d = data.data;
                    if (!d) {
                        setLocalStorage('ifBindWxUser', false)
                        delLocalStorage('yueuserH5')
                        changeUrl("index");
                        return;
                    }
                    if (d.status != 0) {
                        setLocalStorage('subStatus', d.subStatus);
                        changeUrl(d.subStatus, d.orderUuid + '&status=' + d.status);
                    }
                },
                function (data) {
                    setLocalStorage('ifBindWxUser', false)
                    delLocalStorage('yueuserH5')
                    changeUrl("index");
                }
            )
        }
    })()
    delLocalStorage('actualMobile');//删除换乘人电话号码

    //    \h5初始化


    var $document = $(document);
    // 初始化起点定位数据
    initStartInputData();
    // 浏览器回退监听
    pushHistory('${appName}', '#');
    window.addEventListener("popstate", function (e) {
//            cancelInputOrBack();
        letShow();
    }, false);
    // 初始化--出发时间选择
    var area1 = new LArea();
    area1.init({
        'trigger': '#timeshow', //触发选择控件的文本框，同时选择完毕后name属性输出到该位置
        'valueTo': '#valueTo', //选择完毕后id属性输出到该位置
        'keys': {
            id: 'id',
            name: 'name'
        }, //绑定数据源相关字段id对应valueTo的value属性输出name对应trigger的value属性输出
        'type': 1, //数据源类型
        'data': LAreaData //数据源
    });
    //侧边栏
    $document.on('touchend', '.user-face-icon', function () {
        var isBind = getLocalStorage('ifBindWxUser', 'string');
        if (isBind == 'false') {
            setTimeout(function () {
                layer.open({
                    type: 2,
                    title: "验证手机号，方便司机联系您",
                    area: ['92%', '235px'], //宽高,
                    shadeClose: true,
                    content: '${base}/yue/login'
                });
            }, 60)


        } else if (isBind == 'true') {
            $('.nav_mask').show();
            $('.l-left-nav').show()
        }
    });

    $document.on('touchend', '.nav_mask', function () {
        $('.nav_mask').hide();
        $('.l-left-nav').hide()
    });
    //退出
    $document.on('touchend', '#exit', function () {
        delLocalStorage('ifBindWxUser');
        delLocalStorage('yueuserH5');
        delLocalStorage('validateOpenId');
        delLocalStorage('subStatus');
        delLocalStorage('hasOrder');
        delLocalStorage('comment');
        delLocalStorage('actualMobile');
        delLocalStorage('Estimate');
        window.location.reload();
    });

    //侧边栏 END

    // 点击呼叫专车
    $document.on('touchend', '.btn-call-abled', function () {
        var isBind = getLocalStorage('ifBindWxUser', 'string');
        if (isBind == 'true') {
            isBind = true;
        } else if (isBind == 'false') {
            isBind = false;
        }
        //调用后台接口，判断该OpenId是否绑定乘客，如果没有则注册乘客或者更新乘客
        if (!isBind) {
            setTimeout(function () {
                layer.open({
                    type: 2,
                    title: "验证手机号，方便司机联系您",
                    area: ['92%', '235px'], //宽高,
                    shadeClose: true,
                    content: '${base}/yue/login'
                });
            }, 60)
        } else {
            var hasOrder = +getLocalStorage('hasOrder', 'string');
            var subStatus = getLocalStorage('subStatus', 'string');
            //查找是否有进行中的订单，如果有就跳转页面到进行中的订单
            if (hasOrder != 0) {
//                changeUrl(subStatus);
            } else {
                var url = "${base}/api/v1/passenger/token/specialOrder/addRealtime";
                //起始点距离
                var routeInfo = getLocalStorage('routeInfo', 'object');
                // 起点信息
                var startLocation = getLocalStorage(START_LOCATION_INFO, 'object');
                // 终点信息
                var endLocation = getLocalStorage(END_LOCATION_INFO, 'object');
                // 预估价信息
                var Estimate = getLocalStorage(estimate, 'object');

                var departTime = getTimeStemp();//预约单有的预约时间
                var actualMobile = "";
                if ($('#changeCustomerSpan').text().startsWith("尾号")) {
                    actualMobile = getLocalStorage('actualMobile', 'string');//实际乘车人电话，只有写了换乘车人才有值
                }
                var dataParam = {
                    passengerUuid: "${sessionScope.passengerUuid}",//乘客Id
                    origin: startLocation.district + startLocation.address,//起点的详细地址,
                    originTitle: startLocation.name,//起点地址标题,
                    originCity: getLocalStorage('city'),//起点城市,
                    originLng: startLocation.location.lng,//起点精度,
                    originLat: startLocation.location.lat,//起点纬度,
                    originAreaCode: startLocation.adcode,
                    dest: endLocation.district + endLocation.address,//终点的详细地址,
                    carType: Estimate.carModelValuationUuid,//车型计价规则,
                    destTitle: endLocation.name,//终点地址标题,
                    destCity: getLocalStorage('city'),//终点城市,
                    destLng: endLocation.location.lng,//终点精度,
                    destLat: endLocation.location.lat,//终点纬度,
                    actualName: '',//实际乘车人
                    actualMobile: actualMobile,
                    carModelLeavesUuid: Estimate.carModelValuationUuid,//车型计价规则,
                    planTrip: routeInfo.distance / 1000,//预估里程(公里)  (单位是米/m)  取时间 routeInfo.time (单位是秒/s),
                    planFare: Estimate.couponMoney || Estimate.totalFare//预估价格
                };
                //通过选择的时间判断是预约单还是即时单，调用后台接口呼叫专车
                if (getTimeStempDefault0() != '0') {
                    url = "${base}/api/v1/passenger/token/specialOrder/addAppotime";
                    dataParam.departTime = departTime;
                }
                dataParam.orderSource = 2;
                yun.ajax_md5(dataParam, url, function (data) {
                        changeUrl(data.data.subStatus, data.data.uuid);
                    }, function (data) {
                        delLocalStorage(inOrder);
                        layer.msg(data.msg);
                    }
                )
            }
        }
    });

    // 起点输入touchend
    $document.on('touchend', '#qidian_input', function (event) {
        event.stopPropagation();
        // 禁止弹出软键盘
        document.activeElement.blur();
        setInputValue('start', 'qidian_input', START_LOCATION_INFO);
    });

    // 终点输入
    $document.on('touchend', '#zhongdian_input', function (event) {
        event.stopPropagation();
        // 禁止弹出软键盘
        document.activeElement.blur();
        setLocalStorage('city', $(this).data('city') || "请选择")
        setInputValue('end', 'zhongdian_input', END_LOCATION_INFO);
    });

    // 输入换乘客人联系方式
    $document.on('touchend', '#changeCustomer', function () {
        layer.open({
            type: 2,
            title: "   ",
            //skin: 'layui-layer-rim', //加上边框
            area: ['80%', '260px'], //宽高,
            shadeClose: false,
            content: '${base}/yue/inputPhone',
//            closeBtn: false
        });
//        addExtraCloseBtn();
    });

    // 自定义关闭按钮
    $document.on('touchend', '#closeExtra', function (event) {
        layer.closeAll();
        $(this).parent('.closeExtraDiv').remove();
    });

    // 选择车型类型
    $document.on('touchend', '#selectCarType', function () {
        var $this = $(this);
        var $span = $this.find('span').eq(0);
        var carTypeId = $span.data('id');
        var carTypeData = getLocalStorage('carTypeData', 'object');
        var carTypeList = $.map(carTypeData, function (elem, index) {
            var obj = {
                id: elem.uuid,
                value: elem.modelName
            }
            return obj;
        });
        var bankSelect = new IosSelect(1, [carTypeList], {
            container: '.container',
            title: '选择车型',
            itemHeight: 50,
            itemShowCount: 3,
            oneLevelId: carTypeId,
            callback: function (selectOneObj) {
                valuation('${sessionScope.passengerUuid}', selectOneObj.id, yun);
                $span.text(selectOneObj.value);
                $span.data('id', selectOneObj.id);
                $span.data('value', selectOneObj.value);
            }
        });
    });

    // 取消
    $document.on('touchend', "#cancelBtn", function (event) {
        $('.amap-sug-result').remove();
        // 如果是起点输入取消时，需要设置定位信息
//        var currentL = getLocalStorage(START_LOCATION_INFO, 'object');
//        setName(currentL.name, currentL.adcode);
        $('#historyBox').addClass('hide').html('');
        $('#searchBox').html('');
        $('#containerBox').removeClass('hide');
        $('.l-footer').removeClass('hide');
        letShow();
        $('.kucity').hide();
    });

    // 起始点搜索input获取焦点监听
    $document.on('focus', "#tipinput", function (event) {
        $('.searchResultList').addClass('hide');
        $('.kucity').hide();
        appendHistory();
    });

    // 起始点搜索input输入监听
    $document.on('keyup input propertychange', "#tipinput", function (event) {

        var $this = $(this),
            keyword = $this.val();

        if (keyword.length > 0) {
            $('#input_delete').removeClass('hide');
            autoComplete(keyword);
        } else {
            $('#input_delete').addClass('hide');
        }
        $('#historyBox').addClass('hide').html('');
    });

    // 历史记录点击
    var toucheFlag = false;
    $document.on('touchstart touchmove touchend', '.history-item', function (event) {
        event.stopPropagation();
        switch (event.type) {
            case 'touchstart':
                toucheFlag = false;
                break;
            case 'touchmove':
                toucheFlag = true;
                break;
            case 'touchend':
                if (!toucheFlag) {
                    var $this = $(this);
                    var $div = $this.clone();
                    $div.find(':nth-child(n)').remove();
                    var name = $div.html();
                    var data = $this.data('item');
                    setName(name, data);
                    letShow();
                    search(data);
                    calculate(yun);
                }
                toucheFlag = false;
                break;
        }
    });

    //    预估费用详情
    $document.on('touchend', '.fare-info', function () {
        layer.open({
            type: 2,
            title: false,
            closeBtn: false,
            shadeClose: false,
            //skin: 'layui-layer-rim', //加上边框
            area: ['100%', '100%'], //宽高,
            shadeClose: true,
            anim: 'up',
            content: '${base}/yue/fareInfo?estimate=Estimate',
            offset: 'lb',
            success: function (index) {
                index.addClass('notradius')
            }
        });
    });

    function setInputValue(from, to, curLocation) {
        $('#containerBox').addClass('hide');
        $('.l-footer').addClass('hide');
        $('#searchBox').removeClass('hide');
        $('#searchBox').load('${base}/yue/' + from);
        $('#curLocation').val(curLocation);
        $('#inputId').val(to);
    }

    function addExtraCloseBtn() {
        var $layer = $('.layui-layer'),
            height = $layer.css('height'),
            top = $layer.css('top'),
            width = $layer.css('width'),
            left = $layer.css('left'),
            zIndex = $layer.css('z-index');

        var $close = $('<div class="closeExtraDiv"><a id="closeExtra" href="javascript:void(0);" style="display: inline-block;"><img src="/images/closeImg.png" /></a></div>');
        var $close = $('<div class="closeExtraDiv">X</div>');

//        top = +(top.substring(0, top.indexOf('px')));
//        height = +(height.substring(0, height.indexOf('px')));
        top = +0;
        height = +0;

        $close.animate({
            'z-index': zIndex,
            'width': width,
            'height': '35px',
            'top': (top + height) + 'px',
            'left': left
        }).find('img').css('height', '80px');

        $close.insertAfter($layer);
    }

    function getCarTypeFromService() {
        var carTypeData = [];
        yun.ajax_md5({}, "${base}/api/v1/passenger/carModelsLevel/list", function (data) {
            console.log(data);
            var data = data.data;
            carTypeData = data;
            setFirstCarType(carTypeData);
            setLocalStorage('carTypeData', carTypeData);
        }, function (data) {
            layer.msg(data.msg);
        })
    }

    getCarTypeFromService();

    function setFirstCarType(data) {
        //默认先用舒适型来预估
        var first = data[0];
        var $trigger = $('#carTypeText');
        $trigger.data('id', first.uuid);
        $trigger.data('value', first.modelName);
        $trigger.text(first.modelName);
        <%--debugger--%>
        <%--valuation('${sessionScope.passengerUuid}',first.uuid);--%>
    }

    //    var promise = getCarTypeFromService();
    //    promise.then(function (data) {
    //        alert('00000000000')
    //        console.log('-------------------0000');
    //        console.log(data);
    //        setFirstCarType(data);
    //        setLocalStorage('carTypeData', data);
    //    });

    function appendHistory() {
        var divHtml = "<div class='amap-sug-result'>";
        var searchHistory = getLocalStorage('searchHistory', 'object');
        if (searchHistory) {
            var len = searchHistory.length;
            if (len > 0) {
                for (var i = 0; i < len; i++) {
                    var item = searchHistory[i];
                    var dataStr = JSON.stringify(item);
                    divHtml += "<div data-item='" + dataStr + "' class='auto-item history-item'" +
                        " id='amap-sug" + i + "'>" + item.name + "<span class='auto-item-span'>" +
                        (item.district || (item.province + item.city + item.name)) + "</span></div>";
                }
                divHtml += "</div>";
                $('#historyBox').removeClass('hide').html(divHtml);
            } else {
                $('#historyBox').addClass('hide').html('');
            }
        }
    }

    function initStartInputData() {
        return;
        var $qidian = $('#qidian_input');
        var currentLocation = getLocalStorage(START_LOCATION_INFO, "object");
//            加入判断此时是否已经存在当前用户定位信息
        if (!currentLocation) {
            setTimeout(function () {
                initStartInputData()
            }, 30);
        } else {
            var location = currentLocation.location;
//            var optionHtml = '<option value="' + currentLocation.adcode + '" data-city="' + currentLocation.district + '" data-lng="' + location.lng + '" data-lat="' + location.lat + '" selected>' + currentLocation.name + '</option>';
//            $qidian.html(optionHtml);
            $qidian.html(currentLocation.name);
            $qidian.data({
                name: currentLocation.name
            })
        }

    }
</script>
</html>